<script setup lang="tsx">
import { CurdData } from '@/api/invoicingInfo/types'
import { saveDataApi, getListApi as getInvoicingInfoListApi, delListApi } from '@/api/invoicingInfo'
import { ElMessageBox } from 'element-plus'

const { push } = useRouter()
const { query } = useRoute()
// 使用 ref 声明响应式变量 isExpanded
const isExpanded = ref(true)

// 切换展开/收起状态的方法
const togglePanel = () => {
  isExpanded.value = !isExpanded.value
}

const props = defineProps({
  currentRow: {
    type: Object as PropType<Nullable<CurdData>>,
    default: () => null
  }
})

const activeName = ref('invoicing_info')

// 控制弹窗显示
const showDialog = ref(false)

// 表单数据，初始化时确保符合 CurdData 结构
const form = ref<CurdData>({
  id: 0,
  customer_id: 0,
  invoice_header: '',
  tax_id_num: '',
  register_phone: '',
  billing_address: '',
  opening_bank: '',
  opening_account: ''
})

// 表单校验规则
const rules = {
  invoice_header: [{ required: true, message: '请输入发票抬头', trigger: 'blur' }],
  tax_id_num: [{ required: true, message: '请输入纳税识别号', trigger: 'blur' }]
}

// 打开弹窗
const addInvoicingInfo = () => {
  showDialog.value = true
  // 如果 currentRow 传入了数据，编辑状态下填充表单
  if (props.currentRow) {
    form.value.customer_id = props.currentRow?.id
  }
}

// 提交表单
const submitForm = async (formRef: any) => {
  formRef.validate(async (valid: boolean) => {
    if (valid) {
      try {
        const response = await saveDataApi(form.value) // 提交数据到 API
          .catch(() => {})
          .finally(() => {})
        if (response) {
          showDialog.value = false
          fetchData()
          ElMessage.success('操作成功')
        }
      } catch (error) {
        console.error('提交失败:', error)
        ElMessage.error('提交失败，请检查网络或稍后重试')
      }
    } else {
      ElMessage.error('请检查表单填写是否正确')
    }
  })
}

const invoicingInfoList = ref<CurdData[]>()

const editInvoicingInfo = (item: CurdData) => {
  form.value = { ...item } // 复制数据
  showDialog.value = true // 打开弹窗
}

const deleteInvoicingInfo = async (id: number) => {
  try {
    await ElMessageBox.confirm('确定要删除此开票信息吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })

    if (invoicingInfoList.value) {
      const response = await delListApi(String(id)) // 调用删除 API
        .catch(() => {})
        .finally(() => {})

      if (response) {
        fetchData() // 重新获取列表数据
        ElMessage.success('操作成功')
      }
      // 本地移除数据，优化用户体验
      invoicingInfoList.value = invoicingInfoList.value.filter((item) => item.id !== id)
    }
  } catch (error) {
    ElMessage.info('操作已取消') // 用户点击取消
  }
}

const fetchData = async () => {
  try {
    const response = await getInvoicingInfoListApi({ customer_id: props.currentRow?.id })
    invoicingInfoList.value = response.data.list
  } catch (error) {
    console.error('获取开票信息失败:', error)
  }
}

fetchData()
// 重置表单
const resetForm = (formRef: any) => {
  formRef.resetFields()
  form.value = {
    id: 0,
    customer_id: form.value.customer_id,
    invoice_header: '',
    tax_id_num: '',
    register_phone: '',
    billing_address: '',
    opening_bank: '',
    opening_account: ''
  }
  showDialog.value = false
}
</script>

<template>
  <el-card shadow="always">
    <div @click="togglePanel" class="header cursor-pointer">
      <span>开票信息</span>
      <div class="actions">
        <el-button size="small" type="primary" @click.stop="addInvoicingInfo()"
          >新建开票信息</el-button
        >
        <!-- <el-button size="small" type="default">新建地址</el-button> -->
      </div>
      <el-icon v-if="isExpanded">
        <el-icon-arrow-down />
      </el-icon>
      <el-icon v-else>
        <el-icon-arrow-right />
      </el-icon>
    </div>
    <el-collapse-transition>
      <div v-show="isExpanded" class="w-full">
        <el-tabs v-model="activeName" type="card" class="demo-tabs">
          <el-tab-pane label="开票信息" name="invoicing_info">
            <el-card shadow="always" class="card-container">
              <div class="flex">
                <div class="info-container" v-for="(item, index) in invoicingInfoList" :key="index">
                  <!-- <div class="info-header">
                    <span class="default-label">默认</span>
                  </div> -->
                  <div class="info-content">
                    <el-descriptions border :column="1" label-align="left" content-align="left">
                      <el-descriptions-item :span="24" label="发票抬头：">{{
                        item.invoice_header
                      }}</el-descriptions-item>
                      <el-descriptions-item :span="24" label="纳税识别号：">{{
                        item.tax_id_num
                      }}</el-descriptions-item>
                      <el-descriptions-item :span="24" label="注册电话："
                        >{{ item.register_phone }}
                      </el-descriptions-item>
                      <el-descriptions-item :span="24" label="开票地址：">{{
                        item.billing_address
                      }}</el-descriptions-item>
                      <el-descriptions-item :span="24" label="开户行：">{{
                        item.opening_bank
                      }}</el-descriptions-item>
                      <el-descriptions-item :span="24" label="开户账号：">{{
                        item.opening_account
                      }}</el-descriptions-item>
                    </el-descriptions>
                  </div>
                  <div class="info-actions">
                    <el-dropdown trigger="click">
                      <el-button type="text" icon="el-icon-more" style="color: blkack"
                        >. . .</el-button
                      >
                      <template #dropdown>
                        <el-dropdown-menu>
                          <el-dropdown-item @click="editInvoicingInfo(item)">编辑</el-dropdown-item>
                          <el-dropdown-item @click="deleteInvoicingInfo(item.id ?? 0)"
                            >删除</el-dropdown-item
                          >
                        </el-dropdown-menu>
                      </template>
                    </el-dropdown>
                  </div>
                </div>
              </div>
            </el-card></el-tab-pane
          >
          <!-- <el-tab-pane label="寄送信息" name="send_info">寄送信息</el-tab-pane> -->
        </el-tabs>
      </div>
    </el-collapse-transition>
  </el-card>

  <!-- 新建开票信息弹窗 -->
  <el-dialog v-model="showDialog" title="开票信息" width="600px" @close="resetForm($refs.formRef)">
    <el-form ref="formRef" :model="form" :rules="rules" label-width="120px">
      <!-- 隐藏 customer_id -->
      <el-form-item prop="id" style="display: none">
        <el-input v-model="form.id" type="hidden" />
      </el-form-item>

      <el-form-item prop="customer_id" style="display: none">
        <el-input v-model="form.customer_id" type="hidden" />
      </el-form-item>
      <el-form-item label="发票抬头" prop="invoice_header">
        <el-input v-model="form.invoice_header" placeholder="请输入发票抬头" />
      </el-form-item>
      <el-form-item label="纳税识别号" prop="tax_id_num">
        <el-input v-model="form.tax_id_num" placeholder="请输入纳税识别号" />
      </el-form-item>
      <el-form-item label="注册电话">
        <el-input v-model="form.register_phone" placeholder="请输入注册电话" />
      </el-form-item>
      <el-form-item label="开票地址">
        <el-input v-model="form.billing_address" placeholder="请输入开票地址" />
      </el-form-item>
      <el-form-item label="开户行">
        <el-input v-model="form.opening_bank" placeholder="请输入开户行" />
      </el-form-item>
      <el-form-item label="开户账号">
        <el-input v-model="form.opening_account" placeholder="请输入开户账号" />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="resetForm($refs.formRef)">取消</el-button>
      <el-button type="primary" @click="submitForm($refs.formRef)">确定</el-button>
    </template>
  </el-dialog>
</template>

<style scoped>
.header {
  display: flex;
  height: 40px;
  padding: 0 10px;
  margin-bottom: 10px;
  font-weight: 900;
  cursor: pointer;
  background-color: #f3f3f3;
  border-radius: 5px;
  align-items: center;
  justify-content: space-between;
}

.actions {
  display: flex;
  justify-content: flex-end;

  /* 让.actions元素自动填充剩余空间 */
  flex-grow: 1;

  /* 确保右侧没有额外间距 */
  margin-left: auto;
}

:deep(.is-bordered-label) {
  width: 200px;
}

.flex {
  display: flex;
  flex-wrap: wrap;
}

.card-container {
  display: flex;
  flex-flow: column wrap;
}

.info-header {
  position: absolute;
  top: 8px;
  right: 16px;
  padding: 2px 4px;
  background-color: #f3f3f3;
  border: 1px solid #ddd;
  border-radius: 4px;
}

.info-container {
  position: relative;
  max-width: calc(46%);
  padding: 0.5%;
  margin: 0.5%;
  border: 1px solid #ddd;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgb(0 0 0 / 10%);
  flex-basis: calc(46%);
}

.info-content {
  font-size: 14px;
  line-height: 1.8;
}

.info-actions {
  position: absolute;
  right: 16px;
  bottom: 8px;
}
</style>
